package 构建模式;

import testJ.test1;

/**
 * 像一条链子一样向下执行，某一链检测失败不断续执行
 * 解耦合，单一性原则，一个扣只执行一个功能，可以通过修改扣的执行循序修改验证逻辑
 */
public class 责任链模式 {
    public static void main(test1[] args) {
        Request request = Request.RequestBuilder.build().frequentOk(true).loggedOn(false).builderRequest();
        //这是一条链，检查完 Frequent 后再 检查 LoggedOn
        boolean res = new RequestFrequentOkCheck(new RequestLoggedOnCheck(null)).process(request);
        System.out.println(res);
    }
}
//模拟请求
class Request{
    private boolean loggedOn;
    private boolean frequentOk;

    public Request(boolean loggedOn, boolean frequentOk) {
        this.loggedOn = loggedOn;
        this.frequentOk = frequentOk;
    }
    //建造者模式
    public static class RequestBuilder{
        private boolean loggedOn;
        private boolean frequentOk;
        public static RequestBuilder build(){
            return new RequestBuilder();
        }
        public  RequestBuilder loggedOn(boolean loggedOn){
            this.loggedOn = loggedOn;
            return this;
        }
        public RequestBuilder frequentOk(boolean frequentOk){
            this.frequentOk = frequentOk;
            return this;
        }
        public Request builderRequest(){
            return new Request(this.loggedOn,this.frequentOk);
        }
    }

    public boolean isLoggedOn() {
        return loggedOn;
    }

    public void setLoggedOn(boolean loggedOn) {
        this.loggedOn = loggedOn;
    }

    public boolean isFrequentOk() {
        return frequentOk;
    }

    public void setFrequentOk(boolean frequentOk) {
        this.frequentOk = frequentOk;
    }
}
//责任链抽象类
abstract class Hander{
    private Hander next;

    public Hander(Hander next) {
        this.next = next;
    }

    abstract boolean process(Request request);

    public Hander getNext() {
        return next;
    }

    public void setNext(Hander next) {
        this.next = next;
    }

}
class RequestFrequentOkCheck extends Hander{
    public RequestFrequentOkCheck(Hander next) {
        super(next);
    }

    @Override
    boolean process(Request request) {
        if(request.isFrequentOk()){
            if(null != getNext()){
                //执行下一扣
                if(!getNext().process(request)){
                    return false;
                }
            }
            return true;
        }
        return false;
    }
}
class RequestLoggedOnCheck extends Hander{
    public RequestLoggedOnCheck(Hander next) {
        super(next);
    }

    @Override
    boolean process(Request request) {
        if(request.isLoggedOn()){
            if(null != getNext()){
                //执行下一扣
                if(!getNext().process(request)){
                    return false;
                }
            }
            return true;
        }
        return false;
    }
}